#!/bin/bash
# -* coding: UTF-8 *-

LC_NUMERIC="en_US.UTF-8"
export LC_NUMERIC

DISTDIR=$1
URI=$2
FILE=$3

if [ -z "${DISTDIR}" ] ; then exit 1; fi
if [ -z "${URI}" ]     ; then exit 2; fi
if [ -z "${FILE}" ]    ; then exit 3; fi

if [ "${URI#file://}" != "$URI" ] ; then
    echo "--$(date +'%H:%M:%S')--  $URI"
    echo "           => '$DISTDIR/$FILE'"
    cp -fa "${URI#file://}" "$DISTDIR"
    [ $? -eq 0 ] && exit 0
fi

PKGDIR=$(portageq envvar PKGDIR)
if [ -z "${PKGDIR}" ]  ; then exit 4; fi

if [ "${DISTDIR}" != "${DISTDIR#${PKGDIR}}" ] ; then
    if [ -r /etc/portage/fetch.packages ] ; then
        while read uri ; do
            uri=${uri//#*/}
            [ -z "$uri" ] && continue
            [ "${uri#*://}" = "$uri" ] && continue
            
            if [ "${uri#file://}" != "$uri" ] ; then
                if [ -e "${uri#file://}$FILE" ] ; then
                    echo "--$(date +'%H:%M:%S')--  ${uri#file://}$FILE"
                    echo "           => '$DISTDIR/$FILE'"
                    cp -fa "${uri#file://}$FILE" "$DISTDIR"
                    [ $? -eq 0 ] && exit 0
                fi
            else
                /usr/bin/wget --no-proxy -t 5 -T 60 --passive-ftp -P "$DISTDIR" "$uri$FILE"
                [ $? -eq 0 ] && exit 0
            fi
        done < /etc/portage/fetch.packages
    fi
else
    if [ -r /etc/portage/fetch.distfiles ] ; then
        while read uri ; do
            uri=${uri//#*/}
            [ -z "$uri" ] && continue
            [ "${uri#*://}" = "$uri" ] && continue

            if [ "${uri#file://}" != "$uri" ] ; then
                if [ -e "${uri#file://}$FILE" ] ; then
                    echo "--$(date +'%H:%M:%S')--  ${uri#file://}$FILE"
                    echo "           => '$DISTDIR/$FILE'"
                    cp -fa "${uri#file://}$FILE" "$DISTDIR"
                    [ $? -eq 0 ] && exit 0
                fi
            else
                /usr/bin/wget --no-proxy -t 5 -T 60 --passive-ftp -P "$DISTDIR" "$uri$FILE"
                [ $? -eq 0 ] && exit 0
            fi
        done < /etc/portage/fetch.distfiles
    fi
fi

/usr/bin/wget -t 5 -T 60 --passive-ftp -P "$DISTDIR" "$URI"
exit $?
